<template>
  <div>
    <el-container>
      <el-header>
        <div>
        <div class="header-title">
          社区团购管理中心
        </div>          
        </div>

        <div>
          <el-icon class="header-icon"><Fold /></el-icon>
        </div>
        <div>
          <el-breadcrumb separator="/">
            <el-breadcrumb-item 
              v-for="(item, index) in breadcrumbItems" 
              :key="index"
              :to="item.path ? { path: item.path } : undefined"
            >
              {{ item.name }}
            </el-breadcrumb-item>
          </el-breadcrumb>
        </div>
        <div style="margin-left: 64%">
          <el-popover
            placement="bottom-end"
            width="120"
            trigger="click"
          >
            <template #reference>
              <span class="header-user" style="font-size: 22px;color: #fff;cursor: pointer;">{{ userName }}</span>
            </template>
            
            <div class="user-dropdown">
              <el-button 
                type="danger" 
                size="small" 
                @click="handleLogout"
                style="width: 100%;"
              >
                <el-icon><SwitchButton /></el-icon>
                退出登录
              </el-button>
            </div>
          </el-popover>
        </div>
      </el-header>
      <el-container>
        <el-aside width="300px">
          <el-menu
            :default-active="activeIndex"
            class="sidebar-menu"
            text-color="rgb(85, 85, 85)"
            active-text-color="rgb(255, 3, 0)"
            :unique-opened="true"
            router
            v-loading="menuLoading"
            element-loading-text="加载菜单中..."
          >
            <!-- 动态菜单 -->
            <template v-for="parent in menuData" :key="parent._id">
              <el-sub-menu :index="parent._id">
                <template #title>
                  <el-icon>
                    <component :is="getIcon(parent.icon)" />
                  </el-icon>
                  <span>{{ parent.name }}</span>
                </template>
                <template v-for="child in parent.children" :key="child._id">
                  <el-menu-item :index="child.path" v-if="child.isShow">
                    {{ child.name }}
                  </el-menu-item>
                </template>
              </el-sub-menu>
            </template>
          </el-menu>
        </el-aside>
        <el-main>
          <router-view />
        </el-main>
      </el-container>
    </el-container>
  </div>
</template>
  
<script setup lang="ts">
import { ref, onMounted, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { 
  ElContainer, 
  ElHeader, 
  ElAside, 
  ElMain, 
  ElMenu, 
  ElSubMenu, 
  ElMenuItem,
  ElIcon,
  ElBreadcrumb,
  ElBreadcrumbItem,
  ElPopover,
  ElButton
} from 'element-plus';
import {
  Fold,
  DataAnalysis,
  Document,
  Goods,
  Picture,
  Promotion,
  User,
  Money,
  Setting,
  SwitchButton
} from '@element-plus/icons-vue';
import { permissionAPI } from '../../api/hy.ts';

const route = useRoute();
const router = useRouter();
const activeIndex = ref(route.path || '1');

// 菜单数据 - 初始化为空，等待权限加载
const menuData = ref([]);

// 菜单加载状态
const menuLoading = ref(true);

// 用户姓名
const userName = ref('用户');

// 面包屑数据
const breadcrumbItems = ref([
  { name: '菜单', path: '/' },
  { name: '   ', path: '' },
  { name: '   ', path: '' }
]);

// 图标映射
const iconMap: Record<string, any> = {
  'DataAnalysis': DataAnalysis,
  'Document': Document,
  'Goods': Goods,
  'Picture': Picture,
  'Promotion': Promotion,
  'User': User,
  'Money': Money,
  'Setting': Setting
};

// 获取图标组件
const getIcon = (iconName: string) => {
  return iconMap[iconName] || Setting;
};

// 更新面包屑
const updateBreadcrumb = () => {
  const currentPath = route.path;
  let parentMenu = null;
  let currentMenu = null;
  
  // 遍历菜单数据查找当前路由对应的菜单
  for (const parent of menuData.value) {
    for (const child of parent.children) {
      if (child.path === currentPath) {
        parentMenu = parent;
        currentMenu = child;
        break;
      }
    }
    if (currentMenu) break;
  }
  
  // 更新面包屑数据
  if (parentMenu && currentMenu) {
    breadcrumbItems.value = [
      { name: '菜单', path: '/' },
      { name: parentMenu.name, path: '' },
      { name: currentMenu.name, path: currentPath }
    ];
  }
};

// 从token中解析用户信息
const getUserInfoFromToken = () => {
  const token = localStorage.getItem('accessToken');
  if (!token) return null;
  
  try {
    const parts = token.split('.');
    if (parts.length !== 3) return null;
    
    // 处理base64url编码
    let base64 = parts[1].replace(/-/g, '+').replace(/_/g, '/');
    
    // 补齐padding
    const padLength = 4 - (base64.length % 4);
    if (padLength < 4) {
      base64 += '='.repeat(padLength);
    }
    
    // 解码base64并正确处理UTF-8字符
    const decoded = decodeURIComponent(
      atob(base64)
        .split('')
        .map(c => '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2))
        .join('')
    );
    
    return JSON.parse(decoded);
  } catch (error) {
    console.error('Token解析失败:', error);
    return null;
  }
};

// 获取用户权限菜单
const fetchUserMenu = async () => {
  try {
    // 从token中获取用户信息和权限
    const tokenPayload = getUserInfoFromToken();
    if (tokenPayload) {
      userName.value = tokenPayload.realName || tokenPayload.userName || '用户';
      
      // 从token中获取用户权限
      const userPermissions = tokenPayload.permissions || [];
      
      if (userPermissions.length > 0) {
        // 获取所有权限树
        const response: any = await permissionAPI.getPermissionTree();
        if (response.code === 200) {
          const allPermissions = response.data;
          
          // 过滤出用户有权限的菜单
          const userMenu = allPermissions.filter((parent: any) => {
            // 过滤子菜单，只显示用户有权限的子菜单
            const userChildren = parent.children.filter((child: any) => 
              userPermissions.some((p: any) => p._id === child._id)
            );
            
            // 如果有子菜单权限，则显示该父菜单
            if (userChildren.length > 0) {
              parent.children = userChildren;
              return true;
            }
            return false;
          });
          
          menuData.value = userMenu;
          menuLoading.value = false;
          console.log('用户菜单:', menuData.value);
          updateBreadcrumb();
          
          // 根据用户角色跳转到相应页面
          if (route.path === '/dashboard' || route.path === '/') {
            // 检查用户角色，判断是否为管理员
            const userRoles = tokenPayload.roles || [];
            const isAdmin = userRoles.some((role: any) => {
              const roleName = (role.name || role.roleName || '').toLowerCase();
              return roleName.includes('admin') || roleName.includes('管理员') || roleName.includes('系统管理员');
            });
            
            let targetPath = '';
            if (isAdmin) {
              // 管理员跳转到账号管理页面
              targetPath = '/system/account';
            } else {
              // 普通用户跳转到第一个菜单的第一个页面
              if (userMenu.length > 0) {
                const firstMenu = userMenu[0];
                if (firstMenu.children && firstMenu.children.length > 0) {
                  targetPath = firstMenu.children[0].path;
                } else if (firstMenu.path) {
                  targetPath = firstMenu.path;
                }
              }
            }
            
            if (targetPath) {
              router.push(targetPath);
            }
          }
        }
      } else {
        // 如果token中没有权限信息，获取所有菜单（用于测试）
        const response: any = await permissionAPI.getPermissionTree();
        if (response.code === 200) {
          menuData.value = response.data;
          menuLoading.value = false;
          console.log('所有菜单:', menuData.value);
          updateBreadcrumb();
          
          // 根据用户角色跳转到相应页面
          if (route.path === '/dashboard' || route.path === '/') {
            // 检查用户角色，判断是否为管理员
            const userRoles = tokenPayload.roles || [];
            const isAdmin = userRoles.some((role: any) => {
              const roleName = (role.name || role.roleName || '').toLowerCase();
              return roleName.includes('admin') || roleName.includes('管理员') || roleName.includes('系统管理员');
            });
            
            let targetPath = '';
            if (isAdmin) {
              // 管理员跳转到账号管理页面
              targetPath = '/dashboard/system/account';
            } else {
              // 普通用户跳转到第一个菜单的第一个页面
              if (response.data.length > 0) {
                const firstMenu = response.data[0];
                if (firstMenu.children && firstMenu.children.length > 0) {
                  targetPath = firstMenu.children[0].path;
                } else if (firstMenu.path) {
                  targetPath = firstMenu.path;
                }
              }
            }
            
            if (targetPath) {
              router.push(targetPath);
            }
          }
        }
      }
    }
  } catch (error) {
    console.error('获取用户菜单失败:', error);
    menuLoading.value = false;
  }
};

// 监听路由变化
watch(() => route.path, (newPath) => {
  activeIndex.value = newPath || '1';
  updateBreadcrumb();
}, { immediate: false });

// 退出登录
const handleLogout = () => {
  // 清除本地存储的token
  localStorage.removeItem('accessToken');
  localStorage.removeItem('refreshToken');
  
  // 跳转到登录页面
  router.push('/login');
};

onMounted(() => {
  fetchUserMenu();
});
</script>
  
<style lang="scss" scoped>
// 变量定义
$primary-color: #e56565;
$background-color: rgb(220, 217, 217);
$white: white;
$text-color: rgb(85, 85, 85);
$text-secondary: rgb(144, 147, 153);
$active-color: rgb(255, 3, 0);
$hover-bg: rgb(248, 248, 248);
$active-bg: rgb(250, 238, 239);
$shadow-light: 0 0 10px 0 rgba(0, 0, 0, 0.1);
$shadow-dark: 0 0 10px 0 rgba(0, 21, 41, 0.35);

// 容器样式
.el-container {
  height: 100vh;
  background-color: $background-color;
}

// 头部样式
.el-header {
  background-color: $primary-color;
  color: $white;
  display: flex;
  align-items: center;
  height: 80px;
  box-shadow: $shadow-light;
  .header-title {
    width: 272px;
    font-size: 24px;
    font-weight: bold;
    margin-left: 20px;
    color: $white;
  }
  .header-icon {
    font-size: 24px;
  }
  
  // 面包屑样式
  :deep(.el-breadcrumb) {
    .el-breadcrumb__item {
      .el-breadcrumb__inner {
        color: $white !important;
        font-size: 18px;
        font-weight: 500;
        
        &:hover {
          color: rgba($white, 0.8) !important;
        }
        
        a {
          color: $white !important;
          text-decoration: none;
          font-weight: normal !important;
          
          &:hover {
            color: rgba($white, 0.8) !important;
          }
        }
      }
      
      .el-breadcrumb__separator {
        color: $white !important;
        font-size: 18px;
      }
    }
  }
}

// 侧边栏样式
.el-aside {
  background-color: $white;
  box-shadow: $shadow-dark;
  width: 300px;
  min-height: 100vh;
  padding: {
    top: 10px;
    left: 10px;
  }
}

// 侧边栏菜单样式
.sidebar-menu {
  height: 100%;

  .el-sub-menu__title {
    font-size: 18px;
    font-weight: 500;
    padding: 0 10px;
    height: 80px;
    line-height: 80px;

    i {
      font-size: 22px;
    }

    span {
      font-size: 20px;
      margin-left: 10px;
    }

    &:hover {
      background-color: $hover-bg;
      color: $active-color;
    }
  }

  .el-menu-item {
    font-size: 18px;
    padding-left: 30px;
    height: 60px;
    line-height: 60px;

    &:hover {
      background-color: $hover-bg;
      border-left: 4px solid $active-color;
    }

    &.is-active {
      background-color: $active-bg;
      color: $active-color;
    }
  }
}

// 主内容区域样式
.el-main {
  background-color: $white;
  margin: 10px;
  overflow-y: auto;
  min-height: calc(100vh - 70px);
}

// 图标样式
.el-icon {
  margin-right: 10px;
  font-size: 18px;
}

// 用户下拉框样式
.user-dropdown {
  .el-button {
    border: none;
    
    &:hover {
      background-color: #f56c6c;
    }
  }
}
</style> 
